<!DOCTYPE html>
<html lang="cn">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>地址填写</title>

        <!-- ========== Css Files ========== -->
        <link href="../static/css/root.css" rel="stylesheet">

    </head>
  <body>

    <div class="login-form">

        <form method="post" id="formSubmit">

            <div class="top">
                <h1>地址填写</h1>
            </div>

            <div class="form-area">
                
                <div class="group">
                    <input type="text" class="form-control" placeholder="收货人姓名" id="recipient">
                    <i class="fa fa-user"></i>
                </div>

                <div class="group">
                    <input type="text" class="form-control" placeholder="手机号码" id="telNum">
                    <i class="fa fa-phone"></i>
                </div>

                <div class="group">
                    <div class="row">

                        <i class="fa fa-paper-plane"> 市区：</i>

                        <div style="transform: translateX(40%);">
                            <select name="input_province" id="input_province">
                                <option value="" id="sheng">省份</option>
                            </select>
    
                            <select name="input_city" id="input_city">
                                <option value="" id="shi">市区</option>
                            </select>
                        </div>

                    </div>
                </div>

                <div class="group">
                    <input type="text" class="form-control" placeholder="详细地址" id="details">
                    <i class="fa fa-home"></i>
                </div>

            </div>
        </form>
        
        <div class="row">
            <button type="button" class="btn btn-default btn-block" onclick="submit()">保存</button>
        </div>

    </div>

<script type="text/javascript" src="../static/js/cityAndPro.js"></script>

<!-- ================================================
jQuery Library
================================================ -->
<script type="text/javascript" src="../static/js/jquery.min.js"></script>

<!-- ================================================
Sweet Alert
================================================ -->
<script src="../static/js/sweet-alert/sweet-alert.min.js"></script>

<!-- ================================================
Selected Tips
================================================ -->
<script type="text/javascript">
    $(function() {
        var html = "";
        var province_idx;
        $("#input_city").append(html);

        $.each(cityMessage, function(idx, item) {
            if(item.parid == '1'){
            html += "<option value='" + item.regname + "' exid='" + item.regid + "'>" + item.regname + "</option>";
            }
    
        });
        $("#input_province").append(html);
        $("#input_province").change(function(e) {
            var province =$(this).val();
            var cityList = [];
            if(province == "") return;
            $("#input_city option").remove();
            var html = "<option value=''>--请选择--</option>";
            
            $.each(cityMessage, function(idx, item) {
                if(province == item.regname && item.parid == '1') {
                    province_idx=idx
                }
            })
            
            $.each(cityMessage, function(idx, item) {
                if(cityMessage[idx].parid == cityMessage[province_idx].regid) {
                    cityList.push(cityMessage[idx])
                }
            })
            
            if(cityList instanceof Array && cityList.length>0){
                $.each(cityList, function(idx, item) {
                    console.log(item)
                    html += "<option value='" + item.regname + "' exid='" + item.regid + "'>" + item.regname + "</option>";
                    
                });
            }else{
                html += "<option value='" + cityMessage[province_idx].regname + "' exid='" + cityMessage[province_idx].regid + "'>" + cityMessage[province_idx].regname + "</option>";
                    
            }
            $("#input_city").append(html);
        });
    });
</script>

<script type="text/javascript">

    function getParams(key) {
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    };

    async function whenComeIn() {
        var name = document.getElementById("recipient");    // 收件人
        var telNum = document.getElementById("telNum");     // 预留电话
        var sheng = document.getElementById("sheng");       // 选择的省份
        var shi = document.getElementById("shi");           // 选择的市
        var detail = document.getElementById("details");    // 具体信息
        var code = getParams("code");
        
        fetch('http://fanggx.xyz:3357/onload?code=' + code).then(function(res) {
            return res.json();
        }).then(function(myJson) {
            name.value = myJson.name;
            telNum.value = myJson.telNum;

            if ( myJson.a_sheng ) {
                sheng.value = myJson.a_sheng;
                sheng.innerText = myJson.a_sheng;
            }
            
            if ( myJson.a_shi ) {
                shi.value = myJson.a_shi;
                shi.innerText = myJson.a_shi;
            }
            
            detail.value = myJson.detail;
            token = myJson.token;
            localStorage.setItem('token', token);
        });
        
    }
    window.onload = whenComeIn;
    
    async function submit(){
        
        const name = document.getElementById("recipient").value;    // 收件人
        const telNum = document.getElementById("telNum").value;     // 预留电话
        const detail = document.getElementById("details").value;    // 具体信息
        const token = localStorage.getItem("token");
        
        var sheng = document.getElementById("input_province");
        var sheng_index = sheng.selectedIndex;
        var a_sheng = sheng.options[sheng_index].value;  // 选择的省份
        
        var shi = document.getElementById("input_city");
        var shi_index = shi.selectedIndex;
        var a_shi = shi.options[shi_index].value;  // 选择的市
        
        const res = await fetch('/address/tiandizhi', {
            method: 'POST',
            body: JSON.stringify({ token, name, telNum, a_sheng, a_shi, detail }),
            headers: {
                'Content-Type': 'application/json'
            }
        });
        const json = await res.json();
        const { stateCode } = json;

        if ( stateCode == 1 ) {
            swal("地址填写成功！", "请重新登录以检查地址是否成功更改", "success");
        } else if ( stateCode == -1 ) {
            swal("地址填写失败！", "登录身份过期，请重新登录", "error");
        } else if ( stateCode == -2 ) {
            swal("地址填写失败！", "后台出现错误，请重新操作", "error");
        } else if ( stateCode == -3 ) {
            swal("地址填写失败！", "填写的地址内容存在空缺，请全部填写", "error");
        } else if ( stateCode == -100 ) {
            swal("地址填写失败！", "出现未知错误，请重新登录", "error");
        } else {
            swal("地址填写失败！", "出现未知错误，请重新登录", "error");
        }
    };
</script>

</body>
</html>